package main

import (
	"fmt"
	"log"
	"net/rpc"

	"gitee.com/cdsfish/skills/rpc/hello_interface/service"
)

func main() {
	c := NewHelloServiceClient()
	resp := &service.HelloResponse{}
	err := c.Hello(&service.HelloRequest{Name: "cds"}, resp)
	if err != nil {
		panic(err)
	}

	fmt.Println(resp.Message)
}

// 约束客户端
// client.Hello(req , resp)
var (
	_ service.HelloService = (*HelloServiceClient)(nil)
)

func NewHelloServiceClient() *HelloServiceClient {

	//首先是通过rpc.Dial拨号RPC服务, 建立连接
	conn, err := rpc.Dial("tcp", "localhost:1234")

	if err != nil {
		log.Fatal("dialing:", err)
	}
	return &HelloServiceClient{
		conn: conn,
	}
}

type HelloServiceClient struct {
	conn *rpc.Client
}

// 在客户端如何实现hello 接口， rpc ---> server 来实现hello 能力
func (c *HelloServiceClient) Hello(
	in *service.HelloRequest,
	out *service.HelloResponse) error {

	//怎么调用这个 rpc server  暴露的对象的方法呢 ？
	//通过call方法进行调用
	//Call(serviceMethod string ,  args any, reply any) eror
	//serverMethod: servicename.fn

	//服务端的接口被HelloService约束了， 直接传递就可行的

	err := c.conn.Call("HelloService.Hello", in, out)
	if err != nil {
		log.Fatal(err)
	}
	return nil
}
